//
//  CYYSTricksterVC.m
//  CreditAddressBook
//
//  Created by Lee on 15/9/2.
//  Copyright (c) 2015年 Lee. All rights reserved.
//  疑似失信人匹配

#import "CYYSTricksterVC.h"
#import "CYPerson.h"
#import "MJRefresh.h"
#import "CYABTool.h"
#import "CYEscape.h"
#import "MBProgressHUD+MJ.h"
#import "CYTool.h"
#import "UIImageView+WebCache.h"
#import "CYYSDetailVC.h"

static CGFloat _sectionHeight = 17;

@interface CYYSTricksterVC ()<UITableViewDelegate, UITableViewDataSource>

@property(nonatomic, strong) UITableView *ysTableView;

@property(nonatomic, strong) NSMutableArray *ysTricksters;

@property(nonatomic, strong) MJRefreshAutoFooter *footer;

@property(nonatomic, assign) __block int page;//页码
@property(nonatomic, strong) NSArray *nameDics;
@property(nonatomic, strong) NSArray *paginationNames;//分页数据

@property(nonatomic, strong) UIView *cover;
@end

@implementation CYYSTricksterVC

static int _pageSize = 30;

- (NSArray *)paginationNames {
    int pageSize = (int)(self.nameDics.count - _pageSize * self.page);
    if (self.nameDics.count && pageSize > 0) {
        if (!_paginationNames) {
            if (self.nameDics.count < _pageSize) {
                pageSize = (int)self.nameDics.count;
            } else {
                pageSize = _pageSize;
            }
        } else {
            if ((self.nameDics.count - _pageSize * self.page) < _pageSize) {
                pageSize = (int)(self.nameDics.count - _pageSize * self.page);
            } else {
                pageSize = _pageSize;
            }
        }
        NSRange range = {self.page * _pageSize, pageSize};
        _paginationNames = [self.nameDics subarrayWithRange:range];
        return _paginationNames;
    }
    return nil;
}

- (void)setNames:(NSArray *)names {
    _names = names;
    
    NSSet *nameSet = [NSSet setWithArray:names];
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *name in nameSet) {
        NSDictionary *nameDic = @{@"name": [CYTool formatNameToZh:name]};
        [arr addObject:nameDic];
    }
    self.nameDics = arr;
    self.page = 0;
//    [MBProgressHUD showMessage:@"数据加载中" toView:self.view];
    int pageCount = (int)(arr.count/_pageSize) + 1;
    for (int i = 0; i < pageCount; i++) {
        [self loadYsTricksters];
    }
}

- (NSMutableArray *)ysTricksters {
    if (!_ysTricksters) {
        _ysTricksters = [NSMutableArray array];
    }
    return _ysTricksters;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupTable];
    [self setExtraCellLineHidden];
    //刷新
    [self setupRefresh];
}

- (void)setupTable {
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    self.view = tableView;
    self.ysTableView = tableView;
    tableView.contentInset = UIEdgeInsetsMake(0, 0, 40, 0);
    tableView.sectionIndexColor = [UIColor grayColor];
}

#pragma mark - 刷新
- (void)setupRefresh {
    [self.ysTricksters removeAllObjects];
    __weak typeof(self) selfVC = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [selfVC refreshFooterView];
    }];
    [footer setTitle:@"上拉加载更多" forState:MJRefreshStateIdle];
    self.ysTableView.mj_footer = footer;
    self.footer = footer;
}

- (void)refreshFooterView {
    [self loadYsTricksters];
}

/**
 *  匹配疑似失信联系人
 */
- (void)loadYsTricksters {
    NSArray *arr = self.paginationNames;
    if (arr && arr.count) {
        NSString *json = [NSString jsonStringWithArray:arr];
        [CYABTool ysDefaultPersonsWithParams:@{@"data": json} success:^(NSArray *defrs) {
            //        for (CYPerson *person in defrs) {
            //            for (RHPerson *rhperson in self.allPeople) {
            //                if ([person.name isEqualToString:rhperson.name]) {
            //                    person.person = rhperson;
            //                    continue;
            //                }
            //            }
            //        }
//            self.view = self.ysTableView;
            
            [self.ysTricksters removeAllObjects];
            [self.ysTricksters addObjectsFromArray:defrs];
            [self.ysTableView reloadData];
            //以动画效果显示数据
//            [CYTool cellAnimationWithTableView:self.ysTableView];
            [self.footer endRefreshing];
            self.page++;
            
            [MBProgressHUD hideHUDForView:self.ysTableView];
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.ysTableView];
//            self.view = self.ysTableView;
            if (error.code == CYErrorCodeNOData) {
                [self.footer endRefreshingWithNoMoreData];
            } else {
              [self.footer endRefreshing];
            }
        }];
    } else {
       [self.footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - table deldgate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.ysTricksters.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CYLog(@"%@",_ysTricksters);
    
    static NSString *ID = @"ysCell";
    CYPerson *cyperson = self.ysTricksters[indexPath.row];
    UITableViewCell *cell = nil;
    cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    cell.textLabel.text = cyperson.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"疑似%ld条记录",(long)cyperson.count];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.textColor = [UIColor redColor];
    if (cyperson.person.thumbnail) {
        [cell.imageView setImage:cyperson.person.thumbnail];
    } else {
        UIImage *cellImage = [UIImage imageWithImage:[UIImage imageNamed:@"ic_contact_info_header"] scaledToSize:CGSizeMake(45, 45)];
        [cell.imageView setImage:cellImage];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.imageView.layer.cornerRadius = 22.5;
    cell.imageView.layer.masksToBounds = YES;
    cell.imageView.layer.borderColor = [CYNaviThemeColor CGColor];
    cell.imageView.layer.borderWidth = 1;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //设置点击效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CYPerson *cyperson = self.ysTricksters[indexPath.row];
    
    CYYSDetailVC *control = [[CYYSDetailVC alloc] init];
    control.person = cyperson;
    control.hidesBottomBarWhenPushed = YES;
    [self.navi pushViewController:control animated:YES];
}
/**
 *  必须要实现titleForHeaderInSection方法才会调用该方法
 */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    //添加显示view
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CYScreeSize.width, _sectionHeight)];
    view.backgroundColor = self.view.backgroundColor;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, self.view.width, _sectionHeight - 1)];
    [view addSubview:label];
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = [UIColor grayColor];
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, _sectionHeight - 1, self.view.width, 1)];
    [view addSubview:line];
    line.backgroundColor = [UIColor groupTableViewBackgroundColor];

    //设置标题
    label.text = [NSString stringWithFormat:@"共%lu人", (unsigned long)self.ysTricksters.count];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60 ;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @" ";
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return _sectionHeight;
}

#pragma mark -
- (void)setExtraCellLineHidden {
    UIView *view =[[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [self.ysTableView setTableFooterView:view];
}

@end
